package com.tiankun.eurekauserinfo.controller;

import com.tiankun.eurekauserinfo.exception.BusinessException;
import com.tiankun.eurekauserinfo.pojo.Order;
import com.tiankun.eurekauserinfo.pojo.OrderGoods;
import com.tiankun.eurekauserinfo.proxy.GoodsHandler;
import com.tiankun.eurekauserinfo.service.OrderService;
import com.tiankun.eurekauserinfo.service.ShoppingCartService;
import com.tiankun.eurekauserinfo.utils.JsonResult;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created with IntelliJ IDEA
 * User: bear
 * Date: 2020/11/13
 * Description
 * Version: V1.0
 */
@RestController
@RequestMapping("shoppingCart")
@CrossOrigin   //用于实现跨域的注解
public class ShoppingCartController {

    @Resource
    ShoppingCartService shoppingCartService = null;
    @Resource
    OrderService orderService = null;
    @Resource
    RedisTemplate redisTemplate = null;


     /*
    这里类似于ribbon，提供一个对外访问的接口地址，
    然后根据ServiceFeignByShow接口来决定调用哪一个子模块服务和哪一个接口地址
     */

    @Resource
    private GoodsHandler goodsHandler;


    @PostMapping(value = "addShop", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Map addShop(@RequestBody Map<String, Object> map) {
        JsonResult jsonResult = new JsonResult();

        Long aLong = shoppingCartService.addShop(String.valueOf(map.get("userPhone")), (Integer) map.get("shopId"), (Integer) map.get("number"));
        if (aLong != 0) {
            jsonResult.setMsg("添加成功");
            jsonResult.setCode("200");
        } else {
            throw new BusinessException("添加失败");
        }
        //获取到商品id，用户电话号码和商品数量
        //添加信息到redis数据库里面

        return jsonResult.getValues();
    }

    @PostMapping(value = "getList", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map getList(@RequestBody Map<String, Object> map) {
        JsonResult jsonResult = new JsonResult();
        //定义一个list集合，用来存放购物车的所有商品信息
        List<Map<String, Object>> list = new ArrayList<>();
        //得到user购物车里面的所有商品id
        Map<String, Object> userPhone = shoppingCartService.getList((String) map.get("userPhone"));
        //得到所有的shopId
        Set<String> godIds = (Set<String>) userPhone.get("godIds");
        //获得在购物车中的的商品数量
        Map entries = (Map) userPhone.get("entries");
        //通过商品id到Goods模块获取商品信息
        //循环遍历每一个shopId，得到商品的详细信息
        for (String godId : godIds) {
            //设置规定的传参格式
            Map<String, Integer> goodsDetail = new HashMap<>();
            //用一个零时的map用来存放商品的详情信息
            Map<String, Object> goods = new HashMap<>();
            goodsDetail.put("godId", Integer.valueOf(godId));
            //得到通过id查询到的商品详细信息(一个list集合)
            Object data = goodsHandler.goodsDetails(goodsDetail).get("data");
            System.out.println(data);
            System.out.println(data.getClass());
            //商品的基本信息
            goods.put("goodsDetail", data);
            //添加在购物车的商品数量
            goods.put("number", entries.get(godId));
            //将商品的详情信息用list集合存放起来
            //格式：{{number：，goodsDetail：[]}}
            list.add(goods);
        }
        jsonResult.setCode("200");
        jsonResult.setMsg("购物车的所有商品信息");
        jsonResult.setData(list);
        return jsonResult.getValues();
    }

    @PostMapping(value = "delete", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map deleteShopCart(@RequestBody Map<String, Object> map) {
        JsonResult jsonResult = new JsonResult();
        List<Integer> list = (List) map.get("list");
        String userPhone = (String) map.get("userPhone");
        shoppingCartService.deleteList(list, userPhone);
        jsonResult.setMsg("以从购物车中删除");
        jsonResult.setCode("200");
        return jsonResult.getValues();
    }

    @PostMapping(value = "settle", produces = MediaType.APPLICATION_JSON_VALUE)
    public Map settle(@RequestBody Map<String, Object> map) {
        JsonResult jsonResult = new JsonResult();
        HashOperations hashOperations = redisTemplate.opsForHash();
        List<Map<String, Object>> godDetails = (List<Map<String, Object>>) map.get("godDetails");
        String userPhone = (String) map.get("userPhone");
        for (Map<String, Object> godDetail : godDetails) {
            Integer godId = (Integer) godDetail.get("godId");
            Integer godNumber = (Integer) godDetail.get("godNumber");
            //修改redis上面的购物车信息
            Long increment = hashOperations.increment("shop" + userPhone, String.valueOf(godId), -Long.valueOf(godNumber));
            if (increment == 0L) {
                hashOperations.delete("shop" + userPhone, String.valueOf(godId));
            }
        }
        //添加订单
        String orderRandom = orderService.addOrder(userPhone, godDetails);

        //通过订单号查询订单详情
        Order order = orderService.findByOrderId(orderRandom);
        if (order == null) {
            throw new BusinessException("订单不存在，请稍后再试");
        }
        //设置规定的传参格式(夸模块通信获取商品详细信息)
        Map<String, Integer> fGoodsDetail = new HashMap<>();
        //定义一个list集合，用来存放订单的所有信息
        List<Map<String, Object>> fList = new ArrayList<>();
        //给map一个商品的id 先获取到订单中的详情信息
        List<OrderGoods> goods = order.getGoods();
        for (OrderGoods orderGoods : goods) {
            //按规定传参夸模块获取商品信息
            //1.取的循环遍历商品取得商品id
            fGoodsDetail.put("godId", orderGoods.getGoodsId());
            //2.得到商品详情接口返回的数据
            Object data = goodsHandler.goodsDetails(fGoodsDetail).get("data");
            //用一个零时的map用来存放商品的详情信息
            Map<String, Object> goodsData = new HashMap<>();
            //3.得到商品详细信息
            goodsData.put(String.valueOf(orderGoods.getId()), data);
            fList.add(goodsData);
        }
        //获取到商品的详情
        //用一个map来存放订单详情，其中内容包括订单，以及商品详细信息
        Map<String, Object> orderDetail = new HashMap<>();
        orderDetail.put("order", order);
        //整个订单的所有商品的所有信息
        orderDetail.put("goodsDetail", fList);
        jsonResult.setData(orderDetail);
        jsonResult.setMsg("订单创建成功");
        jsonResult.setCode("200");

        return jsonResult.getValues();

    }
}
